<template>
  <div class="header">
    <div class="header-nav">
      <a href="javascript:;" @click="clickMenu('logo')">
        <img :src="personLogo?personLogo:'static/img/logo2.png'" class="header-logo">
      </a>
      <div style="right: 10px;top: 0;position: absolute;">
        <div class="company-cascader" v-show="meta == 'realTime'|| isreportHome">
          <el-select v-if="isreportHome?companyOptions.length>1:companyOptions.length"
                     v-model="company_id"
                     @change="companyChange">
            <el-option
              v-for="item in companyOptions"
              :key="item.id"
              :label="item.company_name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <!--<el-cascader class="company-cascader" v-if="headOn=='realTime'?true:false"-->
        <!--:options="companyOptions"-->
        <!--v-model="company_id_arr"-->
        <!--:placeholder="'选择所属企业'"-->
        <!--:show-all-levels="false"-->
        <!--:props="{-->
        <!--expandTrigger:'hover',-->
        <!--checkStrictly:'true',-->
        <!--}"-->
        <!--@change="companyChange">-->
        <!--</el-cascader>-->
        <img src="static/img/userimg.jpg" alt="">
        <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              {{userName}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="add"
                              v-if="meta == 'realTime'">配置驾驶舱
            </el-dropdown-item>
            <el-dropdown-item command="update">权限刷新</el-dropdown-item>
            <el-dropdown-item command="changepwd" divided>修改密码</el-dropdown-item>
            <el-dropdown-item command="logout" divided>登出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <ul class="headul">
        <li v-for='item in columnList' :key='item.id'>
          <el-dropdown v-if="item.menu_code == 'realTime' && (item.children.length > 1)"
                       @command="clickMenu(item.menu_url)" class="link"
                       :class="meta==item.menu_url?'router-link-exact-active router-link-active router-link-active':''">
              <span>
                {{item.menu_name}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="dropdownItem in item.children" :key="dropdownItem.menu_url"
                                :disabled="dropdownItem.menu_url == active">
                <router-link :to='dropdownItem.menu_url'>
                  {{dropdownItem.menu_name}}
                </router-link>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <div v-else @click="clickMenu(item.menu_url)">
            <router-link v-if="item.menu_url == 'realTime'" class="link"
                         :class="meta==item.menu_url?'router-link-exact-active router-link-active router-link-active':''"
                         :to='{name:item.children[0].menu_url}'>
              {{item.menu_name}}
            </router-link>
            <router-link v-else class="link"
                         :class="meta==item.menu_url?'router-link-exact-active router-link-active router-link-active':''"
                         :to='{name:item.menu_url}'>
              {{item.menu_name}}
            </router-link>
          </div>
        </li>
      </ul>
    </div>

    <!-- <color-picker v-show="false"></color-picker> -->
    <div class="header-message" :class="meta=='realTime'||headOn=='realTime'?'jsc':''">
        <img class="header-msg-store" src="static/img/store.png">
        <span>{{headName}}</span>
      <div class="extra">
        <!-- <i class="iconfont icon-tianqi"></i>
        <p>天气：多云&nbsp;26℃-30℃</p> -->
        <span>{{nowTime}}</span>
      </div>
    </div>
    <el-dialog
      title="修改密码"
      :visible.sync="changepwd"
      class="indivdialog changepwd"
      v-dialogDrag
      @close="reForm"
      width="40%"
      top='12vh'
      center
    >
      <el-form :model="FormVal" status-icon :rules="resetFormRules" ref="FormVal" label-width="80px">
        <el-form-item label="旧密码" prop="oldpwd">
          <el-input type="password" v-model="FormVal.oldpwd" autofocus auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newpwd">
          <el-input type="password" v-model="FormVal.newpwd" auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="renewpwd">
          <el-input type="password" v-model="FormVal.renewpwd" auto-complete="off" show-password></el-input>
        </el-form-item>
        <el-form-item class="formButton">
          <el-button type="primary" @click="submitForm('FormVal')">提 交</el-button>
          <el-button @click="changepwd=false">取 消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>
</template>
<style lang="scss">
  * {
    box-sizing: border-box;
  }
  .header {
    padding: 0px;
    height: 92px;
    .header-nav {
      width: 100%;
      height: 50px;
      position: relative;
       background-color:#fff;
       box-shadow: 0px 0px 40px rgba(85,128,255,0.1);
      .header-logo {
        position: absolute;
        transform: translateY(-50%);
        top: 50%;
        left: 23px;
        max-width: 120px;
        max-height: 37px;
        vertical-align: middle;
      }
      ul {
        margin-left: 220px;
        line-height: 50px;
        li {
          display: inline-block;
          .link {
            color: #000;
            padding: 0 24px;
            font-size: 14px;
            cursor: pointer;
            display: inline-block;
            position: relative;
            &::after {
              content: '';
              position: absolute;
              width: 30px;
              height: 4px;
              border-radius: 2px;
              bottom: 1px;
              display: block;
              background: #545deb;
              // background-color: #8EC5FC;
              // background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);
              left: 50%;
              margin-left: -15px;
              opacity: 0;
              transform: scale(0, 1);
              transition: all 0.3s;
            }

            &:hover {
              color: #545deb;

              &::after {
                opacity: 1;
                transform: scale(1, 1);
                transition: all 0.3s;
              }
            }

            &.router-link-exact-active {
              color: #545deb;

              &::after {
                opacity: 1;
                transform: scale(1, 1);
                transition: all 0.3s;
              }
            }
          }
        }


      }

      div {
        img {
          display: inline-block;
          width: 28px;
          height: 28px;
          line-height: 54px;
          border-radius: 50%;
          vertical-align: middle;
          margin-right: 2px;
        }
      }

      .el-dropdown {
        &:first-child {
          margin-right: 15px;
        }

        .el-dropdown-link {
          .icon-shezhi {
            vertical-align: middle;
          }

          cursor: pointer;
          display: inline-block;
          color: #000;
          line-height: 54px;
        }
      }
    }
    
    .company-cascader {
      display: inline-block;
      width: 200px;

      .el-input__inner {
        border: none;
        background: #fff;
      }
    }

    .header-message {
      height: 42px;
      line-height: 42px;
      width: 100%;
      background: #f4f4fa;
      padding: 0 20px 0 230px;
      &.jsc{
        padding: 0 20px 0 18px;
      }
      .header-msg-store {
        width: 30px;
        display: inline-block;
        vertical-align: text-top;
      }
      > span {
        cursor: default;
        font-weight: 600;
        font-size: 15px;
      }
      .extra {
        float: right;

        .iconfont {
          font-size: 20px;
          color: #ffc834;
        }

        p {
          display: inline-block;
          margin: 0 35px 0 5px;
          font-size: 14px;
        }

        span {
          font-size: 14px;
          font-weight: bold;
          color: #000;

          &:last-child {
            margin-left: 15px;
          }
        }
      }
    }

    .changepwd {
      padding: 40px;

      .el-input {
        margin: 10px 0;
      }

    }

    .el-form-item__label {
      line-height: 60px;
    }

    .formButton {
      margin: 0;
      text-align: center;

      .el-form-item__content {
        margin: 0 !important;

        .el-button {
          margin: 0 10px;
        }
      }
    }


  }

  body {
    .el-dropdown-menu {
      top: 41px !important;

      .el-dropdown-menu__item {
        padding: 0 40px;
      }

      .el-dropdown-menu__item--divided {
        &::before {
          height: 0;
        }
      }
    }

    .el-cascader-panel {
      .el-cascader-menu {
        .el-cascader-menu__wrap {
          .el-cascader-node {
            .el-checkbox, .el-radio {
              width: 100%;
              height: 100%;
              position: absolute;
              z-index: 1;
              left: 0;
              padding-left: 20px;

              .el-radio__input {
                top: 50%;
                transform: translateY(-50%);
              }
            }
            .el-cascader-node__label {
              padding-left: 25px;
            }
          }
        }
      }
    }
  }
</style>
<script>
  // import colorPicker from "@/components/common/color"; //颜色
  let moment = require("moment");
  export default {
    data() {
      //修改密码表单验证
      var validatePass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入新密码'));
        } else if (value.toString().length < 6 || value.toString().length > 18) {
          callback(new Error('密码长度为6 - 18个字符'))
        } else if (value === this.FormVal.oldpwd) {
          callback(new Error('新密码不能与旧密码相同!'))
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.FormVal.newpwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入旧密码'));
        } else if (value.toString().length < 6 || value.toString().length > 18) {
          callback(new Error('密码长度为6 - 18个字符'))
        } else {
          callback();
        }
      };
      return {
        personLogo: '',                //个性化logo
        changepwd: false,              //修改密码弹出层
        gotopshow: true,
        nowTime: moment().format('YYYY-MM-DD  HH:mm:ss'),   //实时时间
        bg: '#e8edf6',
        columnList: [],//头部菜单列表
        userName: '用户名',//用户名
        list: [
          {
            name: "酷炫黑",
            color: '#333333',
            key: 'black'
          },
          {
            name: '商务蓝',
            color: '#2780c4',
            key: 'blue'
          },
          {
            name: '少女粉',
            color: '#ffc0cb',
            key: 'pink'
          }
        ],
        FormVal: {
          newpwd: '',
          renewpwd: '',
          oldpwd: '',
        },
        resetFormRules: {
          newpwd: [
            {required: true, validator: validatePass, trigger: 'blur'}
          ],
          renewpwd: [
            {required: true, validator: validatePass2, trigger: 'blur'}
          ],
          oldpwd: [
            {required: true, validator: validatePass3, trigger: 'blur'}
          ]
        },
        headOn: "",//头部菜单长度
        active: "",//选的哪个
        companyOptions: [],//企业树结构
        company_id_arr: [],//选择企业arr
        company_id: [],//选择企业
        time:null,
        meta: this.$route.meta.type,
      }
    },
    props: ['menu', 'headName','showRealTime','isreportHome'],
    components: {
      // colorPicker
    },
    watch: {
      menu(val) {
        this.columnList = val
        if (this.showRealTime) {
          this.columnList.map(x => {
            if (x.menu_url == 'realTimeChain') x.menu_name = '实时数据驾驶舱(连锁店)'
            if (x.menu_url == 'realTimeMall') x.menu_name = '实时数据驾驶舱(购物中心)'
          })
        }
        this.headOn = localStorage.headerActive || localStorage.active;
        this.active = localStorage.active;
      },
    },
    created() {},
    mounted() {
      this.getPersonConfig();
      if (localStorage.PersonConfig) {
        let model = JSON.parse(localStorage.PersonConfig);
        this.personLogo = model.logo;
        this.setTitleLink(model.titleLink)
      } else {
        this.getPersonConfig();
      }
      this.columnList = this.menu ? this.menu : [];
      //判断是否显示驾驶舱的种类
      if(this.showRealTime){
        this.columnList.map(x => {
          if (x.menu_url == 'realTimeChain') x.menu_name = '实时数据驾驶舱(连锁店)'
          if (x.menu_url == 'realTimeMall') x.menu_name = '实时数据驾驶舱(购物中心)'
        })
      }

      this.headOn = localStorage.headerActive || localStorage.active;
      this.active = localStorage.active;
      if (localStorage.userName) this.userName = localStorage.userName
      if (localStorage.UserThemeColor) this.bg = localStorage.UserThemeColor
      //判断是否是驾驶舱页面或者报表home页，如果是则调用企业树接口
      this.$nextTick(() => {
        if (this.meta === 'realTime'|| this.isreportHome) {
          this.getCompanyTree()
        }
      })
      this.time = setInterval(() => {
        this.nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
      }, 1000);
    },
    beforeDestroy() {
      clearInterval(this.time);
      this.time = null
    },
    methods: {
      // header菜单选中
      // pitchOn(){
      //    let eqindex=0;
      //    for(let i in this.menu){
      //      if(this.$route.meta.type == this.menu[i].menu_url){
      //        eqindex = i
      //      }
      //    }
      //   $('.headul li').children('a').removeClass('router-link-exact-active');
      //   if($('.headul li').children('a').length> this.menu.length)
      //   eqindex=(eqindex*2)+1;
      //   $('.headul li').eq(eqindex).children('a').addClass('router-link-exact-active');
      // },
      //获取企业树
      getCompanyTree() {
        let url = '/sys/report_assist_new/company_tree'
        this.$api.get(url)
        .then(data => {
          if (data == '10001') {
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading', false);
            return
          }
          if (data) {
            this.companyOptions = data.data;
            this.company_name = data.data[0].parent_name_list[0];
            this.company_id = data.data[0].id;
            this.$Bus.$emit('companyData', this.companyOptions[0]);
          }
        })
        .catch(err => {
          console.log(err, '错');
        })
      },

      //企业树change事件
      companyChange(val) {
        // console.log(val,'val');
        // console.log(this.companyOptions,'this.companyOptions');
        for (let i in this.companyOptions) {
          if (val === this.companyOptions[i].id) {
            this.$Bus.$emit('companyData', this.companyOptions[i]);
            return
          }
        }
      },

      //下拉菜单下拉框点击事件
      handleCommand(val) {
        if (val == 'changepwd') {
          this.changepwd = true;
        } else if (val == 'add') {
          this.$Bus.$emit('indivconfig', val);
        } else {
          this.$emit(val)
        }
      },
      //头部菜单点击事件，存储所点击的菜单，在column组件中获取到来渲染对应的菜单列表
      clickMenu(val) {
        // console.log(val);
        if (val == "logo") {
          localStorage.setItem('headerActive', 'index');
          this.$router.push('/');
        } else {
          localStorage.setItem('headerActive', val);
        }
      },
      //修改密码提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$Bus.$emit('Loading', true);
            let dataval = {
              old_pwd: this.FormVal.oldpwd,
              new_pwd: this.FormVal.newpwd
            };
            let mode = {};
            mode.old_pwd = dataval.old_pwd;
            mode.new_pwd = dataval.new_pwd;   //  ?old_pwd='+dataval.old_pwd+'&new_pwd='+dataval.new_pwd
            let url = '/sys/user/modify-pwd';
            this.$api.post(url, mode)
            .then(data => {
              if (data == '10001') {
                this.$message.error('无权操作该数据')
                this.$Bus.$emit('Loading', false);
                return
              }
              // console.log(data,'000')
              if (data) {
                this.$message({type: 'success', message: '修改成功，请重新登陆'});
                localStorage.removeItem('token');
                localStorage.removeItem('isRoot');
                sessionStorage.removeItem('menu')
                sessionStorage.removeItem('buttonPermissions');
                this.$nextTick(() => {
                  this.$router.push('login');
                })
              } else {
                this.FormVal.oldpwd = "";
                this.$Bus.$emit('Loading', false);
              }
            }).catch(err => {
               console.log(err, '修改密码错误');
              this.$Bus.$emit('Loading', false);
            });
          } else {
            return false;
          }
        });
      },
      //重置修改密码表单
      reForm(formName) {
        this.$refs.FormVal.resetFields();
      },
      //获取个性化配置
      getPersonConfig() {
        let url = 'noauth/get-system-personalise';
        this.$api.get(url).then(data => {
          if (data == '10001') {
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading', false);
            return
          }
          if (data.data) {
            // console.log(data.data);
            if (Object.keys(data.data.data_value).length > 0) {
              //  let mode={};
              //  mode.loginLogoShow=data.data.data_value.loginLogoShow,
              //  mode.loginSite=data.data.data_value.loginSite;
              //  mode.loginbg=data.data.data_value.loginbg;
              //  mode.logo=data.data.data_value.logo;
              this.personLogo = data.data.data_value.logo;
              this.setTitleLink(data.data.data_value.titleLink)
              localStorage.setItem('PersonConfig', JSON.stringify(data.data.data_value));
            }
          }

        }).catch(err => {
           console.log(err);
        })
      },
      setTitleLink(href){
        let titleLink = document.getElementById('titleLink')
        titleLink.href = href ? href : 'static/img/favicon.jpg'
      }
    },
  }
</script>
